<template>
    <div>
    <el-card shadow="hover" style="width: 100%;min-height: 700px;background: #ffffff">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-row>
                <el-col :span="12" style="margin-top: 20px">
                    <el-form-item label="标题" prop="articleTitle">
                        <el-input v-model="ruleForm.articleTitle" style="width: 300px"></el-input>
                    </el-form-item>
                    <el-form-item label="摘要" prop="articleDescription">
                        <el-input type="textarea" style="width: 300px" v-model="ruleForm.articleDescription"></el-input>
                    </el-form-item>
                    <el-form-item label="文章分区" prop="sortId">
                        <el-select v-model="ruleForm.sortId" multiple placeholder="请选择">
                            <el-option
                                    v-for="item in sortOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="标签" prop="labelId">
                        <el-tag
                                :key="index"
                                v-for="(tag,index) in ruleForm.labelId"
                                closable
                                :disable-transitions="false"
                                @close="handleClose(tag)">
                            {{tag}}
                        </el-tag>
                        <el-input
                                class="input-new-tag"
                                v-if="inputVisible"
                                v-model="inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm"
                                @blur="handleInputConfirm"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                    </el-form-item>
                    <el-form-item label="可看程度" prop="articleCan">
                        <el-radio-group v-model="ruleForm.articleCan">
                            <el-radio :label="1">私密</el-radio>
                            <el-radio :label="2">公开</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12" style="margin-top: 20px">
                    <el-form-item label="封面">
                        <el-upload
                                class="avatar-uploader"
                                action="/Oss/uploadImgFile"
                                :show-file-list="false"
                                :headers="headers"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="ruleForm.articleCover" :src="ruleForm.articleCover" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="内容" prop="articleContent">
                <mavon-editor v-model="ruleForm.articleContent"
                              ref="md"
                              @change="change"
                              @imgAdd="imgAdd"></mavon-editor>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm',1)">立即创建</el-button>
                <el-button type="primary" @click="submitForm('ruleForm',2)">保存为草稿</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                headers: {
                    Authorization: window.sessionStorage.getItem('tokenStr')
                },
                // 自定义标签
                inputVisible: false,
                inputValue: '',
                ruleForm: {
                    "userId": null,
                    "articleTitle": null,
                    "articleDescription": null,
                    "articleCover": null,// 封面
                    "articleContent": null,
                    "articleViews": null,
                    "articleCommentCount": null,
                    "articleDate": null,
                    "articleLikeCount": null,
                    "articleType": null,
                    "articleTop": null,
                    "articleCan": null,
                    sortId: [], // 分区id
                    labelId: [],
                },
                rules: {
                    articleTitle: [
                        {required: true, message: '请输入标题', trigger: 'blur'},
                        {min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur'}
                    ],
                    articleDescription: [
                        {required: true, message: '请输入摘要', trigger: 'blur'}
                    ],
                    sortId: [
                        {required: true, message: '请输入内容', trigger: 'blur'}
                    ],
                    labelId: [
                        {required: true, message: '请输入内容', trigger: 'blur'}
                    ],
                    articleCan: [
                        {required: true, message: '请输入内容', trigger: 'blur'}
                    ],
                    articleContent: [
                        {required: true, message: '请输入内容', trigger: 'blur'}
                    ],
                },
                sortOptions: [],
            };
        },
        methods: {
            submitForm(formName, type) {
                this.ruleForm.articleType = type;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.postRequest('/articles/insert/'+this.ruleForm.labelId+'/'+this.ruleForm.sortId,this.ruleForm).then(resp => {
                                if(resp){
                                    this.$router.push({
                                        path: "/common/CommonBlog",
                                    });
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 将图片上传到服务器，返回地址替换到md中
            imgAdd(pos, $file) {
                // this.$refs.md.$img2Url(pos, 'http://blacktry.oss-cn-beijing.aliyuncs.com/2021/06/28/d53216984ebe4ff69fd805b4453ffbb9.png');
                let formdata = new FormData();
                formdata.append('file', $file);
                //访问后台服务器方法
                this.postRequest('/Oss/uploadImgFile',formdata, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
                    if (res) {
                        this.$refs.md.$img2Url(pos, res.data);
                    } else {
                        this.$message.error("插入图片失败！")
                    }

                }).catch(err => {
                    console.log(err)
                })
            },
            change(value, render) {
                this.html = render;
            },
            handleClose(tag) {
                this.ruleForm.labelId.splice(this.ruleForm.labelId.indexOf(tag), 1);
            },

            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                    console.log(_);
                });
            },

            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    this.ruleForm.labelId.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            // 上传封面
            handleAvatarSuccess(res) {
                this.ruleForm.articleCover = res.data;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 10;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 10MB!');
                }
                return isJPG && isLt2M;
            },
            initSortOptions() {
                this.getRequest('/sorts/selectSortOptions').then(resp => {
                    if (resp) {
                        this.sortOptions = resp;
                    }
                })
            },
            initSort() {
                this.getRequest('/sorts/backOneSortOptions/' + this.$route.query.id).then(resp => {
                    if (resp) {
                        this.ruleForm.sortId = resp;
                    }
                })
            },
            initLabel() {
                this.getRequest('/labels/backOneLabelsOptions/' + this.$route.query.id).then(resp => {
                    if (resp) {
                        this.ruleForm.labelId = resp;
                    }
                })
            },
            initBlog(){
                if (this.$route.query.id) {
                    this.getRequest('/articles/selectOneArticle/' + this.$route.query.id).then(resp => {
                        if (resp) {
                            // this.ruleForm = resp.data;
                            Object.assign(this.ruleForm,resp.data)
                        }
                    })
                }
            },
        },
        created() {
            this.initSortOptions();
                if (this.$route.query.id) {
                    this.initBlog();
                    this.initLabel();
                    this.initSort();
                }
        }
    }
</script>
<style>
    .el-tag + .el-tag {
        margin-left: 10px;
    }

    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>